package com.caineng.zhaobiao.zbapi.utils.ip;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caineng.zhaobiao.zbapi.utils.cache.CacheUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip) {
        String address = UNKNOWN;
        // 内网不查询
        if (IpUtils.isLocalAddr(ip)) {

            return "内网IP";
        }
        String key = "ip:"+ip;
        String addressCache = (String) CacheUtils.get(key);
        if(StrUtil.isNotBlank(addressCache)) {
            return addressCache;
        }else{
            try {
                String rspStr = HttpUtil.get(IP_URL + "?ip=" + ip + "&json=true");
                if (StrUtil.isEmpty(rspStr)) {
                    log.error("获取地理位置异常 {},返回的结果是:" + rspStr, ip);
                    return address;
                }
                JSONObject obj = JSONUtil.parseObj(rspStr);
                log.info("==>" + obj);
                String region = obj.getStr("pro");
                String city = obj.getStr("city");
                String addr = obj.getStr("addr");
                address=String.format("%s %s %s", region, city, addr);
                CacheUtils.put(key,address);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取地理位置异常 {}" + e.getMessage(), ip);
            }
        }
        return address;
    }

    public static String getRealAddressByIP_GEO(HttpServletRequest request) {
        String ip = request.getParameter("ip");
        if(StrUtil.isBlank(ip)) {
            ip = AddressUtils.getRealIpAddr(request);
        }
        String address = "";
        // 内网不查询
        if (IpUtils.isLocalAddr(ip)) {
            log.error("内网ip不显示geo信息");
            return "";
        }
        try {
            String rspStr = HttpUtil.get(IP_URL+ "?ip=" + ip + "&json=true");
            if (StrUtil.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {},返回的结果是:"+rspStr, ip);
                return "";
            }
            JSONObject obj = JSONUtil.parseObj(rspStr);
            log.info("==>"+obj);
            String region = obj.getStr("pro");
            String city = obj.getStr("city");
            return String.format("%s-%s", region, city);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取地理位置异常 {}"+e.getMessage(), ip);
        }

        return address;
    }

    /**
     * 获取客户端的ip地址
     * @param request
     * @return
     */
    public static String getRealIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     *  获取客户端端口
     */
    public static String getClientPort(HttpServletRequest request) {
        String port = request.getRemotePort()+"";
        return  port;
    }


    public static void main(String[] args) {
        String name =getRealAddressByIP("222.240.102.248");
        System.out.println(name);
    }
}
